package day9;

import java.util.concurrent.locks.ReentrantLock;

class MyRunnable5 implements Runnable {
    static int tickets = 10;
    static Float t = new Float(3.14);
    static ReentrantLock lock = new ReentrantLock();

    @Override
    public void run() {
        boolean flag = true;
        while (flag) {
            flag = sel(flag);
        }
    }

    private static boolean sel(boolean flag) {
        try {
            lock.lock();
            if (tickets > 0) {
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName() + "正在售票" + (tickets--) + "票");
            } else {
                flag = false;
            }
            return flag;
        } catch (Exception e){
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
        return flag;
    }
}

public class 同步方法Demo5 {
    public static void main(String[] args) {
        MyRunnable5 mr = new MyRunnable5();
        Thread t1 = new Thread(mr, "南昌西站");
        Thread t2 = new Thread(mr, "南昌站");
        Thread t3 = new Thread(mr, "南昌东站");

        System.out.println("mr: " + mr);

        t1.start();
        t2.start();
        t3.start();
    }
}
